package com.base.imgs.glide.transformation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.support.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.TransformationUtils;

import jp.wasabeef.glide.transformations.BitmapTransformation;

/**
 * 只获取倒影图片
 * 倒影为原图的高度的一半
 * Created by zhouzechao on 2018/1/5.
 */

public class OnlyReflectedTransformation extends BitmapTransformation {

    private final int radius;

    public OnlyReflectedTransformation(int radius) {
        this.radius = radius;
    }

    @Override
    public String key() {
        return "ReflectedTransformation()";
    }

    @Override
    protected Bitmap transform(@NonNull Context context, @NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        final int reflectionGap = 4;//原图与倒影之间的间隙

        int size = Math.max(outWidth, outHeight);

        Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, size, size);
        bitmap.setHasAlpha(true);

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1); // 实现图片的反转
        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0,
                size / 2, size, size / 2, matrix, false); // 创建反转后的图片Bitmap对象，图片高是原图的一半
        Bitmap bitmapWithReflection = Bitmap.createBitmap(size,
                size / 2, Bitmap.Config.ARGB_8888);

        Canvas canvas1 = new Canvas(bitmapWithReflection);

        Paint paint = new Paint();
        canvas1.drawRect(0, 0, size, reflectionGap, paint);
        canvas1.drawBitmap(reflectionImage, 0, reflectionGap, null);

        paint = new Paint();
        LinearGradient shader = new LinearGradient(0,
                bitmap.getHeight(), 0,
                bitmapWithReflection.getHeight() + reflectionGap,
                0x33ffffff, 0x00ffffff, Shader.TileMode.MIRROR);// 创建线性渐变LinearGradient对象
        paint.setShader(shader); // 绘制
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));//倒影遮罩效果
        canvas1.drawRect(0, 0, size, bitmapWithReflection.getHeight()
                + reflectionGap, paint);

        return bitmapWithReflection;
    }
}
